package me.wangxuan.pat.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import lombok.Data;
import lombok.EqualsAndHashCode;
import me.wangxuan.pat.entity.Account;
import me.wangxuan.pat.entity.Project;

@Data
@EqualsAndHashCode(callSuper = false)
public class AccountManageDialog extends JDialog {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger("global");
	private DefaultTableModel tableModel;
	private JTable recordTable;
	private List<Account> records;
	private JButton addButton;
	private JButton deleteButton;
	private JButton updateButton;
	private List<Project> projects;

	public AccountManageDialog(JFrame owner, List<Account> records, List<Project> projects) {
		super(owner, "账号管理", true); // 模态对话框
		// 设置窗口大小
		setSize(800, 600);
		// 设置窗口布局
		setLayout(new BorderLayout());
		// 初始化记录列表
		this.records = records;
		this.projects = projects;

		// 初始化表格模型
		tableModel = new DefaultTableModel(new Object[] { "账号ID", "账号名称", "所属项目", "接口域名", "账号配置" }, 0) {
			private static final long serialVersionUID = 1L;

			// 覆盖 isCellEditable 方法
			@Override
			public boolean isCellEditable(int row, int column) {
				// 返回 false 表示该单元格不可编辑
				// 例如，这里我们将所有单元格设为不可编辑
				return false; // 或者根据需要返回 true/false
			}
		};
		JPanel searchPanel = new JPanel();
		searchPanel.setLayout(new FlowLayout());
		List<Project> pList = new ArrayList<>();
		pList.addAll(projects);
		Project pAll = new Project();
		pAll.setProjectId(0L);
		pAll.setProjectName("全部");
		pList.add(0, pAll);
		
		JComboBox<Project> projectBox = new JComboBox<>(pList.toArray(new Project[0]));
		searchPanel.add(projectBox);
		JButton searchButton = new JButton("查询");
		searchPanel.add(searchButton);
		add(searchPanel, BorderLayout.NORTH);
		
		for (Account a : records) {
			tableModel.addRow(new Object[] { a.getAccountId(), a.getAccountName(), a.getProject().getProjectName(),
					a.getDomain(), a.getConfigs() });
		}
		// 初始化表格
		recordTable = new JTable(tableModel);

		// 创建表格面板
		JScrollPane scrollPane = new JScrollPane(recordTable);
		add(scrollPane, BorderLayout.CENTER);
		// 创建按钮面板
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new FlowLayout());
		// 添加按钮：增加、删除、修改、查询
		addButton = new JButton("增加");
		deleteButton = new JButton("删除");
		updateButton = new JButton("修改");

		// 将按钮添加到按钮面板
		buttonPanel.add(addButton);
		buttonPanel.add(deleteButton);
		buttonPanel.add(updateButton);

		// 将按钮面板添加到窗口底部
		add(buttonPanel, BorderLayout.SOUTH);
	}

	public class AddRecordForm extends JDialog {
		private static final long serialVersionUID = 1L;
		// 定义标签和文本框的宽度
		int labelWidth = 100;
		int textFieldWidth = 250;
		private JPanel formPanel;
		private JComboBox<Project> projectBox;
		private JTextField accountName;
		private JTextField domain;
		private List<JTextField> fields;
		private Account result;

		public AddRecordForm(JFrame owner, List<Project> projects, Account a) {
			super(owner, "增加记录", true); // 模态对话框
			this.result = a;
			// 设置窗口大小
			setSize(850, 600);
			// 设置窗口布局
			setLayout(new BorderLayout());

			// 创建表单面板
			formPanel = new JPanel();
			formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS)); // 使用 BoxLayout.Y_AXIS 实现垂直排列

			JPanel panel1 = new JPanel();
			panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
			JLabel label1 = new JLabel("所属项目:");
			label1.setPreferredSize(new Dimension(labelWidth, label1.getPreferredSize().height));
			panel1.add(label1);
			projectBox = new JComboBox<Project>(projects.toArray(new Project[0]));
			projectBox.setPreferredSize(new Dimension(textFieldWidth, projectBox.getPreferredSize().height));
			panel1.add(projectBox);
			formPanel.add(panel1);

			JPanel panel2 = new JPanel();
			panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
			JLabel label2 = new JLabel("账号名称:");
			label2.setPreferredSize(new Dimension(labelWidth, label2.getPreferredSize().height));
			panel2.add(label2);
			accountName = new JTextField();
			accountName.setPreferredSize(new Dimension(textFieldWidth, accountName.getPreferredSize().height));
			panel2.add(accountName);
			formPanel.add(panel2);

			JPanel panel3 = new JPanel();
			panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
			JLabel label3 = new JLabel("接口域名:");
			label3.setPreferredSize(new Dimension(labelWidth, label3.getPreferredSize().height));
			panel3.add(label3);
			domain = new JTextField();
			domain.setPreferredSize(new Dimension(textFieldWidth, domain.getPreferredSize().height));
			panel3.add(domain);
			formPanel.add(panel3);
			
			Project selected = (Project) projectBox.getSelectedItem();
			logger.info("selected:" + selected);
			if (selected == null) {
				selected = projectBox.getItemAt(0);
			}
			if (result != null) {
				projectBox.setSelectedItem(result.getProject());
				accountName.setText(result.getAccountName());
				domain.setText(result.getDomain());
			}
			fields = new ArrayList<>();
			initExtendFields(selected, result);

			// 创建按钮面板
			JPanel buttonPanel = new JPanel();
			buttonPanel.setLayout(new FlowLayout());

			// 创建“确定”按钮
			JButton okButton = new JButton("确定");
			okButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					// 获取用户输入的数据
					Project selected = (Project) projectBox.getSelectedItem();
					String aName = accountName.getText().trim();
					String dm = domain.getText().trim();
					// 验证输入是否为空
					if (aName.isEmpty()) {
						JOptionPane.showMessageDialog(AddRecordForm.this, "请填写账号名称！");
						return;
					}

					// 创建新记录
					if (result == null) {
						result = new Account();
					}
					result.setAccountName(aName);
					result.setDomain(dm);
					result.setProject(selected);
					JSONObject cfgs = new JSONObject();
					for (JTextField field : fields) {
						cfgs.put((String) field.getClientProperty("fieldName"), field.getText());
					}
					result.setConfigs(cfgs.toString());
					// 关闭对话框
					dispose();

				}
			});

			// 创建“取消”按钮
			JButton cancelButton = new JButton("取消");
			cancelButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					// 清空输入框
					accountName.setText("");
					domain.setText("");
					fields.clear();
					// 关闭对话框
					dispose();
				}
			});

			// 将按钮添加到按钮面板
			buttonPanel.add(okButton);
			buttonPanel.add(cancelButton);

			add(formPanel, BorderLayout.CENTER);
			add(buttonPanel, BorderLayout.SOUTH);
		}

		private void initExtendFields(Project p, Account a) {
			String cfg = p.getAccountConfigs();
			JSONArray ja = JSON.parseArray(cfg);
			Map<String, Object> map = new HashMap<>();
			if (a != null) {
				String cfgs = a.getConfigs();
				if(JSON.isValidArray(cfgs)) {
					JSONArray cfgArray = JSON.parseArray(cfgs);
					for (int i = 0; i < cfgArray.size(); i++) {
						JSONObject o = cfgArray.getJSONObject(i);
						for (String key : o.keySet()) {
							map.put(key, o.get(key));
						}
					}
				}else if(JSON.isValidObject(cfgs)) {
					JSONObject json = JSON.parseObject(cfgs);
					for(String k :json.keySet()) {
						map.put(k, json.get(k));
					}
				}
			}
			for (int i = 0; i < ja.size(); i++) {
				JSONObject o = ja.getJSONObject(i);
				JPanel panel = new JPanel();
				panel.setLayout(new FlowLayout(FlowLayout.CENTER));
				JLabel label = new JLabel(o.getString("desc") + ":");
				label.setPreferredSize(new Dimension(labelWidth, label.getPreferredSize().height));
				panel.add(label);
				JTextField field = new JTextField();
				field.putClientProperty("fieldName", o.getString("name"));
				field.setPreferredSize(new Dimension(textFieldWidth, field.getPreferredSize().height));
				if (map.containsKey(o.getString("name"))) {
					field.setText(String.valueOf(map.get(o.getString("name"))));
				}
				fields.add(field);
				panel.add(field);
				formPanel.add(panel);
			}
		}

		// 获取用户输入的记录
		public Account getRecord() {
			return result;
		}
	}

}
